#include <bits/stdc++.h>
using namespace std;
deque<int> q;//双端队列
int n, op, x;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main()
{
	scanf("%d", &n);
	for (int i = 0; i < n; i++)
	{
		scanf("%d", &op);
		switch (op)
		{
		case 1:
		{
			scanf("%d", &x);
			q.push_front(x);
			break;
		}
		case 2:
		{
			scanf("%d", &x);
			q.push_back(x);
			break;
		}
		case 3:
		{
			printf("%d\n", q.front());
			break;
		}
		case 4:
		{
			printf("%d\n", q.back());
			break;
		}
		case 5:
		{
			q.pop_front();
			break;
		}
		case 6:
		{
			q.pop_back();
			break;
		}
		}
	}
	return 0;
}
